package com.ewzj.bigdata.mvp.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.ewzj.bigdata.R;
import com.ewzj.bigdata.app.utils.RegexUtils;
import com.ewzj.bigdata.app.utils.RxUtils;
import com.ewzj.bigdata.di.component.DaggerRegisterComponent;
import com.ewzj.bigdata.di.module.RegisterModule;
import com.ewzj.bigdata.mvp.contract.RegisterContract;
import com.ewzj.bigdata.mvp.presenter.RegisterPresenter;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.functions.Function3;
import io.reactivex.functions.Predicate;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class RegisterFragment extends BaseFragment<RegisterPresenter> implements RegisterContract.View {


    @BindView(R.id.et_pass)
    EditText etPass;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_verifycode)
    EditText etVerifycode;
    @BindView(R.id.tv_register)
    TextView tvregister;
    @BindView(R.id.tv_getcode)
    TextView tvgetcode;
    public static RegisterFragment newInstance() {
        RegisterFragment fragment = new RegisterFragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(AppComponent appComponent) {
        DaggerRegisterComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .registerModule(new RegisterModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_register, container, false);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        initEdit();
    }

    private void initEdit() {
        Observable<CharSequence> _phoneChangeObservable = RxTextView.textChanges(etPhone).skip(1);
        Observable<CharSequence> _passwordChangeObservable = RxTextView.textChanges(etPass).skip(1);
        Observable<CharSequence>   _numberChangeObservable = RxTextView.textChanges(etVerifycode).skip(1);
        Observable.combineLatest(_phoneChangeObservable, _passwordChangeObservable, _numberChangeObservable,
                new Function3<CharSequence, CharSequence, CharSequence, Boolean>() {
                    @Override
                    public Boolean apply(CharSequence charSequence, CharSequence charSequence2, CharSequence charSequence3) throws Exception {
                        Boolean phone=RegexUtils.checkPhone(charSequence.toString());
                        Boolean pass=RegexUtils.checkPassword(charSequence2.toString());
                        Boolean code=TextUtils.isEmpty(charSequence3);
                        return phone&&pass&&code;
                    }
                }).subscribe(new ErrorHandleSubscriber<Boolean>(ArmsUtils.obtainAppComponentFromContext(getActivity()).rxErrorHandler()) {
            @Override
            public void onNext(Boolean aBoolean) {
                tvregister.setSelected(true);
            }
        });
    }

    /**
     * 此方法是让外部调用使fragment做一些操作的,比如说外部的activity想让fragment对象执行一些方法,
     * 建议在有多个需要让外界调用的方法时,统一传Message,通过what字段,来区分不同的方法,在setData
     * 方法中就可以switch做不同的操作,这样就可以用统一的入口方法做不同的事
     * <p>
     * 使用此方法时请注意调用时fragment的生命周期,如果调用此setData方法时onCreate还没执行
     * setData里却调用了presenter的方法时,是会报空的,因为dagger注入是在onCreated方法中执行的,然后才创建的presenter
     * 如果要做一些初始化操作,可以不必让外部调setData,在initData中初始化就可以了
     *
     * @param data
     */

    @Override
    public void setData(Object data) {

    }


    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }


    @OnClick({R.id.tv_getcode, R.id.tv_register})
    public void onViewClicked(View view) {
        String stringphone=etPhone.getText().toString();
        switch (view.getId()) {
            case R.id.tv_getcode:
                sendSms(stringphone);
                break;
            case R.id.tv_register:
                String stringpass=etPass.getText().toString();
                String stringcode=etVerifycode.getText().toString();
                register(stringphone,stringpass,stringcode);
                break;
        }
    }

    private void sendSms(String phone){
        tvgetcode.setEnabled(false);
        Observable.interval(1, TimeUnit.SECONDS)
                .compose(RxUtils.applySchedulersWithoutLoading(this))
                .takeWhile(new Predicate<Long>(){
                    @Override
                    public boolean test(Long num) throws Exception {
                        return num<60;
                    }
                })
                .subscribe(new ErrorHandleSubscriber<Long>(ArmsUtils.obtainAppComponentFromContext(getActivity()).rxErrorHandler()) {
            @Override
            public void onNext(Long aLong) {
                if (aLong==59){
                    tvgetcode.setEnabled(true);
                    tvgetcode.setText(getString(R.string.send_sms));
                }else {
                    tvgetcode.setEnabled(false);
                    tvgetcode.setText(60-aLong+"秒后获取");
                }
            }
        });
        if (TextUtils.isEmpty(phone)){
            ArmsUtils.snackbarText(getString(R.string.empty_phone));
            return;
        }
        if (!RegexUtils.checkMobile(phone)){
            ArmsUtils.snackbarText(getString(R.string.unright_phone));
            return;
        }
        mPresenter.sendSms(phone);
    }
    private void register(String phone,String pass,String code){
        if (TextUtils.isEmpty(phone)){
            ArmsUtils.snackbarText(getString(R.string.empty_phone));
            return;
        }
        if (!RegexUtils.checkMobile(phone)){
            ArmsUtils.snackbarText(getString(R.string.unright_phone));
            return;
        }

        if (TextUtils.isEmpty(pass)){
            ArmsUtils.snackbarText(getString(R.string.empty_pass));
            return;
        }
        if (!RegexUtils.checkPassword(pass)){
            ArmsUtils.snackbarText(getString(R.string.unright_pass));
            return;
        }
        if (TextUtils.isEmpty(code)){
            ArmsUtils.snackbarText(getString(R.string.empty_pass));
            return;
        }
        mPresenter.register(phone,pass,code);
    }

    @Override
    public Context getbasecontext() {
        return this.getActivity();
    }
}
